/**
 * ReportGear(2011)
 */
package net.abbp.report.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * Dom4j辅助类
 * 
 * @version 1.0 2011-4-13
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class Dom4jUtils {
	/**
	 * 创建Document对象
	 * 
	 * @return Document对象
	 */
	public static Document createDocument() {
		return DocumentHelper.createDocument();
	}

	/**
	 * 根据文本创建Xml文档
	 * 
	 * @param xmlText
	 *            xml文本
	 * @return Xml文档
	 */
	public static Document createDocument(String xmlText) {
		try {
			return DocumentHelper.parseText(xmlText);
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static Document createDocumentFromStream(InputStream stream) {
		SAXReader reader = new SAXReader();
		try {
			return reader.read(stream);
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static Document createDocumentFromFile(String fileName) {
		SAXReader reader = new SAXReader();
		try {
			return reader.read(new File(fileName));
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 写入XML文件
	 * 
	 * @param document
	 *            文档
	 * @param fileName
	 *            文件名
	 */
	public static void writeDocument(Document document, String fileName) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");

			XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
			writer.write(document);

			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
